package LC;

public class LC17 {
    public int canCompleteCircuit (int[] gas, int[] cost) {
        // write code here
        int total = 0, sum = 0;
        int index = -1;
        for (int i = 0; i < gas.length; i++) {
            sum += gas[i] - cost[i];        //本次消耗
            total += gas[i] - cost[i];  //总消耗
            if (sum < 0) {
                sum = 0;
                index = i;    //记录解的位置
            }
        }
        return total >= 0 ? index + 1 : -1;//只要total>=0，肯定有解
    }
}